/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.taglibs.input;

import com.codemagi.util.*;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.*;

/**
 *  This class implements the &lt;input:tinymce&gt; tag, which presents a
 *  &lt;textarea&gt; form element with additional code to implement the 
 *  TinyMCE WYSIWYG HTML editor developed by Moxiecode Systems AB
 *
 *  @version 1.0
 *  @author August Detlefsen (for CodeMagi, Inc.)
 *  @author Moxiecode Systems AB (for TinyMCE) 
 *  @see http://tinymce.moxiecode.com/
 */
public class TinyMCE extends Input {

    private boolean dev = false;
    private String initParams = "";

    public void setDev(String newValue) {
	dev = Boolean.valueOf(newValue);
    }

    public void setDev(Boolean newValue) {
	dev = newValue;
    }

    public void setInitParams(String newValue) {
	initParams = newValue;
    }

    public int doStartTag() throws JspException {
	try {
            // sanity check
            if (name == null || name.equals("")) {
                throw new JspTagException("invalid null or empty 'name'");
	    }
	    
	    // get what we need from the page
	    ServletRequest req = pageContext.getRequest();
	    JspWriter out = pageContext.getOut();
	    
	    //the id attribute to use in markup
	    String mceId = getMceId();

	    // start building up the tag
	    out.println();
	    out.println("<textarea ");
	    out.println("    name=\"" + Util.quote(name) + "\"");
	    out.println("    id=\"" + Util.quote(mceId) + "\"");
	    out.println("    class=\"mceEditor\"");
	    
	    //disable the form field if disabled is set
	    if (disabled) {
		out.println("    readonly=\"readonly\"");
		out.println("    OnFocus=\"blur();\"");
		appendAttribute("style", "cursor:default;");
	    }

	    // include any attributes we've got here
	    Util.printAttributes(out, attributes);
	    
	    //if this is a required field and it is not filled out, do something...
	    if ( !Utils.isEmpty((String)req.getAttribute("error_" + name + "_error")) ) {
                out.println("    class=\"cminput_error\"");
            }

	    // end the starting tag
	    out.println(">");
	    
	    /*
	     * print out the value from the request if it's there, or
	     * use the default value if it's not
	     */
	    String param = getParameter(name, (HttpServletRequest)req);

	    if ( override ) {
		out.print( Util.quote(dVal) );
	    } else if (param != null ) {
		out.print( Util.quote(param) );
	    } else if ( dVal != null ) {
		out.print( Util.quote(dVal) );
	    }
	    
	    // end the textarea
	    out.println("</textarea>");
	
	    // add the TinyMCE javascript code
	    if (dev) {
		out.println("<script type=\"text/javascript\" src=\"/tinymce/jscripts/tiny_mce/tiny_mce_src.js\"></script>");
	    } else {
		out.println("<script type=\"text/javascript\" src=\"/tinymce/jscripts/tiny_mce/tiny_mce.js\"></script>");
	    }
	    out.println("<script type=\"text/javascript\">");
	    out.println("   tinyMCE.init({ ");
	    out.println("      mode : \"exact\",");
	    out.println("      elements : \"" + mceId + "\",");
	    out.println("      convert_urls : false,");
	    out.println("      theme : \"advanced\",");
	    out.println("      theme_advanced_toolbar_location : \"top\",");
	    out.println("      editor_selector : \"mceEditor\",");
	    out.println("      editor_deselector : \"mceNoEditor\",");
	    out.println("      inline_styles : true");
	    
	    if (!Utils.isEmpty(initParams)) 
		out.println(",\n      " + initParams);

	    out.println("   });");
	    out.println("</script>");

	    //show the error message
	    if (showError) { 
		String errorMessage = (String)req.getAttribute(name + "_error_message");
		if (errorMessage != null && !"".equals(errorMessage) ) { 
		    out.print( "<BR><SPAN CLASS=\"input_error_msg\">" + errorMessage + "</SPAN>");
		}
	    }

    
	} catch (Exception ex) {
	    throw new JspTagException(ex.getMessage());
	}
	return SKIP_BODY;
    }

    private String getMceId() {
	return Utils.isEmpty(getMarkupId()) ? UIDGenerator.getUID() : getMarkupId() ;
    }
}

